// stores/counter.js
import { defineStore } from "pinia";
import auth from "@/utils/auth.js";
import apis from "@/apis/index.js";
import utils from "@/utils/utils";
import config from "@/config/index.js";
let { baseUrl } = config;
import atlas from "@/utils/atlas.js"; //地图相关方法
import uniFunc from "@/utils/uniFunc.js"; //二封装uni的方法
import permission from "@/utils/permission.js";

const useCounterStore = defineStore("counter", {
  state: () => ({
    slParams: {
      userInfo: {},
      redirect: "", //路由重定向
      cropperUrl: "", //裁剪图片地址
      token: "", //token
      position: {}, //用户位置信息
      wsStatus: 0,//ws连接状态
      danmakuData: [],//弹幕
    },
    bulletChat: {},//选中的弹幕
    dataRefresh: false, //数据重新加载
  }),

  getters: {
    navBarHeight: (state) => {
      //获取手机系统信息
      const systemInfo = uni.getSystemInfoSync();
      //console.log("[systemInfo]", systemInfo)
      //获取状态栏信息-h5没有状态栏
      let statusBarHeight = systemInfo.statusBarHeight;
      let navBarHeight = 0;
      //获取胶囊信息:uni.getMenuButtonBoundingClientRect-->App | H5 | 支付宝小程序不支持
      // #ifndef H5 || APP-PLUS || MP-ALIPAY
      const menuButtonBoundingInfo = uni.getMenuButtonBoundingClientRect();
      console.log("[胶囊信息]", menuButtonBoundingInfo);
      // (胶囊底部高度-状态栏的高度)+(胶囊顶部高度-状态栏的高度)*2=导航栏的高度
      navBarHeight =
        (menuButtonBoundingInfo.top - systemInfo.statusBarHeight) * 2 +
        (menuButtonBoundingInfo.bottom - systemInfo.statusBarHeight);
      // #endif
      return Number(statusBarHeight) + Number(navBarHeight);
    },
    //底部安全区距离
    systemInfo: (state) => {
      return uni.getSystemInfoSync();
    },
    statusBarHeight() {
      //获取手机系统信息
      const systemInfo = uni.getSystemInfoSync();
      //console.log("[systemInfo]", systemInfo)
      //获取状态栏信息-h5没有状态栏
      return systemInfo.statusBarHeight;
    },
    windowWidth: (state) => {
      //获取手机系统信息
      const systemInfo = uni.getSystemInfoSync();
      //屏幕的宽度
      return systemInfo.windowWidth;
    },
    windowHeight: (state) => {
      //获取手机系统信息
      const systemInfo = uni.getSystemInfoSync();
      //屏幕的高度
      return systemInfo.windowHeight;
    },
    //是否登录
    isLogin: (state) => {
      //获取到手机号和token
      return state.slParams.token;
    },
    //系统信息
    systemInfoSync: (state) => {
      return uni.getSystemInfoSync();
    },
    isLocalHost: (state) => {
      return window.location.hostname.includes("localhost");
    },
    menuButtonInfoWidth: (state) => {
      // #ifdef MP-WEIXIN
      let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
      return menuButtonInfo.width;
      // #endif
      return 0
    },
    userInfo: (state) => {
      return state.slParams.userInfo
    }
  },

  actions: {
    notlogged() {
      utils.showToast("您暂未登录，请先登录");
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage?.route; //当前路由
      setTimeout(() => {
        this.redirect = `/${currentRoute}`;
        utils.toLink("/packagePages/login/login");
      }, 1000);
    },
    async wxLogin() {
      // #ifdef MP-WEIXIN
      let jscode = await auth.login();
      let resp = await apis.getWxOpenId({ jscode });
      uni.setStorageSync("cwydToken", resp);
      await this.getUserData();
      this.getUserData();
      // #endif

      // #ifdef H5
      if (!utils.isWeiXin()) return utils.showToast("请在微信的环境下打开");
      return await this.wxLoginH5();
      // #endif
    },
    //移动端微信登录
    async wxLoginH5() {
      let code = utils.getUrlCode(location.href, "code");
      if (code) {
        let token = await apis.mobileLogin({
          type: "wxH5Login",
          data: { code },
        });
        this.setRelease("token", token);
        await this.getUserData();
      } else {
        await this.getWeChatCode();
      }
    },
    //获取H5微信登录返回的code
    getWeChatCode() {
      const appID = config.appIdH5; //公众号appID
      const callBack = window.location.href; //回调地址 就是你的完整地址登录页

      //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
      window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        appID +
        "&redirect_uri=" +
        encodeURIComponent(callBack) +
        `&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
    },
    //获取用户信息
    async getUserData() {
      let resp = await this.getUserInfo(this.slParams.userId);
      this.setRelease("userInfo", resp);
    },
    init() {
      let slParams = uni.getStorageSync("slParams");
      this.slParams = slParams;
      if (slParams.token) {
        this.getUserData()//获取用户信息
      } else {
        //utils.toLink("/packagePages/login/login");
        slParams.value = {
          userInfo: {},
          redirect: "", //路由重定向
          cropperUrl: "", //裁剪图片地址
          token: "", //token
          danmakuData: [], //弹幕数据
          position: {}, //用户位置信息
        }
      }
    },
    //更新手机号
    async getPhoneNumber(jscode) {
      if (!jscode) return;
      // #ifdef MP-WEIXIN
      await apis.authUserMobile({ code: jscode });
      // #endif
      this.getUserData();
    },


    //上传头像
    uploadHeadImgFile(element) {
      let slParams = uni.getStorageSync("slParams")
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: `${baseUrl}:18087/user/loginReginfo/head`, // 上传的服务器地址
          filePath: element, // 要上传的文件路径
          name: "headPhoto", // 服务器接收文件的字段名
          formData: {},
          header: {
            Authorization: slParams.token,
          },
          success: ({ data }) => {
            let obj = JSON.parse(data)
            resolve(obj.data);
          },
          fail: (err) => {
            console.log(err); // 上传失败的错误信息
          },
        });
      });
    },

    //上传文件
    uploadFile(element, request?) {
      let formData = {}
      let url = `${baseUrl}:18089/movements/saveMovementsPhoto`
      let name = "imageContent"
      if (request == 'savePhoto') {
        url = `${baseUrl}:18087/userDescribe/userDescribe/savePhoto`
        name = "file"
      } else if (request == 'frontUpload') {
        url = `${baseUrl}:18082/api/front/user/upload/image`
        name = "multipart"
        formData['pid'] = 1
        formData['model'] = "product"
      }

      let slParams = uni.getStorageSync("slParams")
      //console.log("拿到的音频", url, element)
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url, // 上传的服务器地址
          filePath: element, // 要上传的文件路径
          name, // 服务器接收文件的字段名
          formData,
          header: {
            Authorization: slParams.token,
          },
          success: ({ data }) => {
            let obj = JSON.parse(data)
            console.log("上传成功", obj)
            resolve(obj.data);
          },
          fail: (err) => {
            utils.showToast(err); // 上传失败的错误信息
            console.log(err); // 上传失败的错误信息
          },
        });
      });
    },

    //七牛上传
    async qiNiuUpload(element) {
      return await toUpload(element)
      function getQIniuInfo() {
        return new Promise((resolve, reject) => {
          uni.request({
            url: 'https://app.taozapp.cn/api/uploadFile/uploadPhoto',
            method: "POST",
          }).then(data => {
            resolve(data.data)
          }).catch(error => {
            reject(error)
          })
        })
      }

      async function toUpload(element) {
        let qiNiuInfo = await getQIniuInfo()
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: "https://upload-z2.qiniup.com",
            filePath: element,
            formData: { token: qiNiuInfo.token },
            name: 'file',
            success: ({ data }) => {
              let imgRes = JSON.parse(data)
              let path = qiNiuInfo.cdnUrl + imgRes.key
              resolve(path)
            },
            fail: (e) => {
              utils.showToast(e)
            }
          })
        })
      }
    },

    //获取用户位置
    async getPosition() {
      try {
        let resp;
        // #ifdef APP-PLUS
        let ret = await this.permissionFunc("location");
        if (ret) resp = await getPosition();
        // #endif

        // #ifndef APP-PLUS
        resp = await getPosition();
        // #endif

        console.log("获取经纬度", resp)

        if (!resp) return;
        this.setRelease("position", resp);

        async function getPosition() {
          let result = await auth.getLocation();
          console.log("获取经纬度", result)
          return result;
        }
      } catch (error) {
        console.log("错误信息", error)
        return {}
      }
    },

    //设置系统参数
    setRelease(type, params) {
      let slParams = uni.getStorageSync("slParams")
      if (!slParams) slParams = {}
      slParams[type] = params;
      uni.setStorageSync("slParams", slParams); //更新缓存
      this.slParams = { ...slParams }
    },

    //退出登录
    async logOut() {
      this.slParams = {
        userInfo: {},
        redirect: "", //路由重定向
        cropperUrl: "", //裁剪图片地址
        token: "", //token
        danmakuData: [], //弹幕数据
        position: {}, //用户位置信息
      }
      uni.removeStorageSync('slParams');//清除指定缓存
      utils.toLink("/packagePages/login/login");
    },

    toParse(code) {
      let url = utils.buildUrl("/packagePages/my/parse", { code })
      utils.toLink(url)
    },
    //APP权限
    async permissionFunc(permissionID, type?) {
      //type 1.重新获取定位
      let msg = {
        refuseContent: "",
        MeetsRequireTitle: "",
        MeetsRequireContent: "",
      };
      //录音
      if (permissionID == "record") {
        msg.refuseContent =
          "由于您拒绝了麦克风权限，请到设置中找到本应用，打开麦克风管理权限";
        msg.MeetsRequireTitle = "申请使用麦克风权限说明";
        msg.MeetsRequireContent =
          "使用场景有：聊天中发送语音；个人资料中音频录制；邂逅约会、恋爱圈、相亲角、一起旅行板块上传本人录音。";
      } else if (permissionID == "storage") {
        //存储
        msg.refuseContent =
          "由于您拒绝了相册存储权限，请到设置中找到本应用，打开相册管理权限";
        msg.MeetsRequireTitle = "申请使用存储空间/照片权限说明";
        msg.MeetsRequireContent =
          "用于上传、下载图片和视频等场景中读取和写入相册和文件内容，使用场景有个人头像；个人相册；客服问题反馈；违规举报；动态、邂逅约会、恋爱圈、相亲角、一起旅行等功能中照片和视频的发布和下载";
      } else if (permissionID == "location") {
        // 地址
        msg.refuseContent =
          "由于您拒绝了位置权限，请到设置中找到本应用，打开位置权限";
        msg.MeetsRequireTitle = "申请使用位置权限说明";
        msg.MeetsRequireContent =
          "用于获取当前您当前的位置";
      }
      let authority = this.sjParams.authority; //有哪些权限
      let MeetsRequire = //已授权
        authority && authority.allow && authority.allow.includes(permissionID);
      let isRefuse =
        authority &&
        authority.refuse &&
        authority.refuse.includes(permissionID); //已永久拒绝

      if (isRefuse) {
        //永久拒绝
        let checkResult = await permission(permissionID);
        if (checkResult.code == 1) {
          let result = checkResult.data;
          if (result == 1) return true;
          else if (type && type == 1) {  //如果是来重新获取定位
          } else {
            return false
          }
        }

        let resp = await utils.showModal({
          content: msg.refuseContent,
          showCancel: false,
        });
        if (!resp) return
        var Intent = plus.android.importClass("android.content.Intent");
        var Settings = plus.android.importClass("android.provider.Settings");
        var Uri = plus.android.importClass("android.net.Uri");
        var mainActivity = plus.android.runtimeMainActivity();
        var intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
        intent.setData(uri);
        mainActivity.startActivity(intent);
        return false;
      } else if (!MeetsRequire) {
        let resp = await utils.showModal({
          title: msg.MeetsRequireTitle,
          content: msg.MeetsRequireContent,
        });
        if (resp) {
          let checkResult = await permission(permissionID);
          if (checkResult.code == 1) {
            let result = checkResult.data;
            if (result == 1) return true;
          }
          return false;
        } else {
          return false;
        }
      } else {
        return true;
      }
    },

    //获取用户信息
    async getUserInfo(userId) {
      return await apis.getUserInfo({ userId });
    },

    //判断是视频还是图片
    isImageOrVideo(url) {
      let type = url.substring(url.lastIndexOf(".") + 1).toLowerCase();
      if (type == "jpg" || type == "png" || type == "jpeg" || type == 'gif') {
        return "image";
      } else if (type == "mp4" || type == "avi" || type == "rmvb" || type == "mov") {
        return "video";
      } else {
        return "other";
      }
    },

    //更新用户在线状态
    async updateUserToken(status) {
      if (!this.isLogin) return;
      await apis.UpdateUserByToken({ status });
    },

    //获取弹幕
    async getBarrage(userId, type?) {
      let data
      if (userId) {
        data = await apis.queryBarrage({ userId });
      } else {
        data = await apis.queryBarrage();
      }
      let list = <any>[]
      data.forEach((element) => {
        element.speed = 3;
        element.style = {
          color: "#fff",
          fontSize: "14px",
          borderRadius: "20.5px",
        };
        if (element.sex == 1) {
          element.style["background"] =
            "linear-gradient(to right, #B658DF, rgba(182,88,223,0.4))";
        } else if (element.sex == 2) {
          element.style["background"] =
            "linear-gradient(to right, #FF8BC7, #FF5BD1)";
        } else {
          element.style["background"] = "linear-gradient(to bottom, #857D77, #777D80,#6C7C86)";
        }
        if (element.id) list.push(element)
      });
      //type 过滤弹幕信息
      return type ? list : data
    },

    //去喜欢
    async toLike(hasLiked, id, type?) {
      //type 1.动态 2.评论
      if (hasLiked == 0) {
        if (type == 1) {
          await apis.movementsLike(id);
        } else {
          await apis.like(id);
        }
      } else {
        if (type == 1) {
          await apis.movementsDisLike(id);
        } else {
          await apis.dislike(id);
        }
      }
    },

    async appPhoneNumberLogin() {
      //定义APP授权弹框
      let univerifyStyle = {
        fullScreen: false,
        icon: { path: "static/img/logo/logo1.jpg" },
        authButton: {
          normalColor: "#FF6D3F",
        },
        privacyTerms: {
          checkedImage: "static/img/logo/select.png", // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)
        },
      };
      let resp = await uniFunc.appPhoneNumberLogin(univerifyStyle);
      //return console.log("APP授权登录", resp);
      let { token, isNew, account } = await apis.oneClickLogin(resp)
      console.log("一键登录", token, isNew, account)
      this.setRelease("token", token);
      this.setRelease("userId", account);
      if (isNew) return utils.toLink("/packagePages/my/baseInfo")
      await this.init();
      utils.toLink("/pages/tabbar/tabbar-1/tabbar-1", "tab");
      uni.closeAuthView(); //关闭一键登录授权界面

      //let phone = await this.getAppPhoneNumber(resp)
      //console.log("解析手机号", phone)
    },

    //App端获取手机号
    getAppPhoneNumber(resp) {
      return new Promise((resolve, reject) => {
        let data = {
          access_token: resp.access_token, // 客户端一键登录接口返回的access_token
          openid: resp.openid, // 客户端一键登录接口返回的openid
        }

        // 在得到access_token后，通过callfunction调用云函数
        uniCloud
          .callFunction({
            name: "appPhoneNumberLogin", // 你的云函数名称
            data,
          })
          .then((res) => {
            let phone = res.result.data.phoneNumber;
            uni.closeAuthView(); //关闭一键登录授权界面
            resolve(phone);
          })
          .catch((err) => {
            console.log("错误原因", err);
          });
      });
    },
  },
});

export default useCounterStore;
